package operativa.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import operativa.bean.entity.Cost;
import operativa.bean.entity.Location;
import operativa.model.dao.CostDAO;
import operativa.model.dao.LocationDAO;
import operativa.model.dto.CostosDTO;
import operativa.utils.Constantes.LocationType;

import org.apache.struts2.ServletActionContext;

import com.mysql.jdbc.StringUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class HarborAbmAction extends ActionSupport implements ModelDriven<Location>, Preparable{
	

	private LocationDAO locationDAO = new LocationDAO();
	private CostDAO costDAO = new CostDAO();

	private static final long serialVersionUID = 1L;
	private List<Location> harborList;
	private Location harbor = new Location();
	
	private List<CostosDTO> costos = new ArrayList<CostosDTO>();
	private Map<String, CostosDTO> costosMap = new HashMap<String, CostosDTO>();
	private List<Location> destinoList = new ArrayList<Location>();
	
	private boolean esEdicion = false;
	
	@Override
	public void prepare() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		esEdicion =!StringUtils.isEmptyOrWhitespaceOnly(request.getParameter("id")); 
		if (esEdicion){
			harbor = locationDAO.findById(Integer.parseInt((request.getParameter("id"))),false);
		}
		
		destinoList = locationDAO.getByTipoUbicacion(LocationType.FISHSHOP.toString());
		for (Location destino : destinoList) {
			CostosDTO nuevo = new CostosDTO(destino);
			costos.add(nuevo);
			costosMap.put(destino.getId().toString(), nuevo);
		}
		
	}

	
	/**
	 * Crea un puerto y calcula los costos a toads los puntos de destino
	 * insertandolos en la tabla COSTO
	 * @return
	 */
	public String save()
	{	
		harbor.setType(LocationType.HARBOR.toString());
		
		this.locationDAO.makePersistent(harbor);
		locationDAO.commit();
		for (CostosDTO costo : costos) {
			Cost nuevo = new Cost();
			//TODO:borrar edicion
			if (esEdicion){
				nuevo = costDAO.findCost(harbor.getId(), costo.getDestino().getId());
			}
			else{
				nuevo = new Cost();
				nuevo.setOrigin(harbor);
				nuevo.setDestination(costo.getDestino());
			}
			System.out.println("COSTO: " + costo.getCosto());
			nuevo.setCost(costo.getCosto());
			if (esEdicion)
				costDAO.persistUpdate(nuevo);
			else
				costDAO.makePersistent(nuevo);
		}
		if (!costos.isEmpty())
			costDAO.commit();
		
		try {
			this.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * Lista todos los puertos
	 * @return
	 */
	public String list()
	{
		harborList = locationDAO.getByTipoUbicacion(LocationType.HARBOR.toString());
		destinoList = locationDAO.getByTipoUbicacion(LocationType.FISHSHOP.toString());
		return SUCCESS;
	}
	
	/**
	 * Borra un puerto
	 * @return
	 */
	public String delete()
	{
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Location toDelete = locationDAO.findById(Integer.parseInt(request.getParameter("id")), false);
		List<Cost> costosABorrar = costDAO.findAllContaining(toDelete.getId());
		System.out.println("CANTIDAD DE COSTOS: " + costosABorrar.size());
		for (int i = 0; i < costosABorrar.size(); i++) {
			System.out.println("Costo: "+ i + " -> " + costosABorrar.get(i).getId());
		}
		costDAO.makeTransient(costosABorrar);
		costDAO.commit();
		locationDAO.makeTransient(toDelete);
		locationDAO.commit();
		return SUCCESS;
	}
	
	/**
	 * Obtiene una unica puerto segun un ID
	 * @return
	 */
	public String edit()
	{
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		harbor = locationDAO.findById(Integer.parseInt((request.getParameter("id"))),false);
		return SUCCESS;
	}
	
	public Location getHarbor() {
		return harbor;
	}

	public void setHarbor(Location fabrica) {
		this.harbor = fabrica;
	}

	public List<Location> getHarborList() {
		return harborList;
	}

	public void setHarborList(List<Location> harborList) {
		this.harborList = harborList;
	}

	@Override
	public Location  getModel() {
		return harbor;
	}

	public List<Location> getDestinoList() {
		return destinoList;
	}

	public void setDestinoList(List<Location> destinoList) {
		this.destinoList = destinoList;
	}


	public List<CostosDTO> getCostos() {
		return costos;
	}


	public void setCostos(List<CostosDTO> costos) {
		this.costos = costos;
	}


	public Map<String, CostosDTO> getCostosMap() {
		return costosMap;
	}


	public void setCostosMap(Map<String, CostosDTO> costosMap) {
		this.costosMap = costosMap;
	}

	

}
